#include "CustomComponents.h"

using namespace juce;

void LevelMeter::paint(Graphics& g)
{
    auto bounds = getLocalBounds().toFloat();
    bounds.setRight(bounds.getRight() - 2.f * bounds.getWidth() / 3.f);
    g.setColour(Colours::black);
    g.fillRect(bounds);

    g.setGradientFill(gradient);
    auto value = valueSupplier();

    value = (value > 6.f ? 6.f : value) < -60.f ? -60.f : value;
    auto scaledY = jmap(value, -60.f, 6.f, 0.f, static_cast<float>(getHeight()));
    g.fillRect(bounds.removeFromBottom(scaledY));

    auto barX = bounds.getRight() + 1.f;
    auto fontX = bounds.getRight() + bounds.getWidth() / 3.f;
    for (float y = -57.f; y <= 3.f; y += 6.f) {
        g.setColour(contourColour);
        scaledY = getHeight() - jmap(y, -60.f, 6.f, 0.f, static_cast<float>(getHeight()));
        auto line = Line<float>(barX, scaledY, fontX - 1.f, scaledY);
        g.drawLine(line);
        auto str = String((int)y);
        str << "dB";
        auto textRect = Rectangle<float>(fontX, scaledY - getHeight() / 22.f,
            bounds.getWidth() * 1.8f, getHeight() / 11.f);
        g.setFont(11);
        g.drawText(str, textRect, juce::Justification::centred);
    }
}

void LevelMeter::resized()
{
    const auto bounds = getLocalBounds().toFloat();
    gradient = ColourGradient { Colours::green, bounds.getBottomLeft(),
        Colours::red, bounds.getTopLeft(), false };
    gradient.addColour(0.5, Colours::yellow);
}

void LevelAlarm::paint(Graphics& g)
{
    auto bounds = getLocalBounds().toFloat();
    auto value = valueSupplier();
    if (value > 1.f && value < 3.f)
        g.setColour(juce::Colours::red);
    else
        g.setColour(juce::Colours::black);
    g.fillRect(bounds);
}

RoundLED::RoundLED(int state, Colour colour) : state(state), colour(colour),
    greenLedImage(juce::ImageCache::getFromMemory(
        BinaryData::greenLed_png, BinaryData::greenLed_pngSize)),
    redLedImage(juce::ImageCache::getFromMemory(
        BinaryData::redLed_png, BinaryData::redLed_pngSize))
{
    
}

void RoundLED::paint(Graphics& g)
{
    auto bounds = getLocalBounds().toFloat();
    if (state == true) {
        g.setColour(colour);
        g.fillEllipse(bounds);

        if (colour == juce::Colours::red)
            g.drawImage(redLedImage, bounds);
        else if (colour == juce::Colours::green)
            g.drawImage(greenLedImage, bounds);
    }
    else {
        g.setColour(juce::Colours::darkgrey);
        g.fillEllipse(bounds);
    }    
}

void RoundLED::setState(bool state)
{
    this->state = state;
    repaint();
}
